<?php

namespace app\admin\controller\parts;

use think\App;
use Throwable;
use app\common\controller\Backend;
use app\common\controller\Approval;
use Overtrue\Pinyin\Pinyin;

/**
 * 配件库存管理
 */
class Info extends Backend
{
    /**
     * Info模型对象
     * @var object
     * @phpstan-var \app\admin\model\parts\Info
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'parts_cost', 'parts_money', 'parts_nur', 'create_time'];

    protected array $withJoinTable = ['manufacturerInfo'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\parts\Info;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['manufacturerInfo' => ['manufacturer_name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $this->PartsCodeIsItRepeated($data["parts_code"],0);
            $pinyin = new Pinyin();
            $data['parts_py'] = str_replace(' ','',$pinyin->abbr($data['parts_name']));
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $this->PartsCodeIsItRepeated($data["parts_code"],1);

            // 数据编辑需要审核通过才执行。
            $OldJson = json_encode($row);
            $NewJson = json_encode($data);
            // 标记已发起审核记录
            $data['is_approval'] = 1;
            $row->save($data);
            //提交记录
            $Approval = new Approval();
            $res = $Approval->AddApprovalRecord($OldJson,$NewJson,0,$data["approval"],$this->auth->id);
            if ($res) {
                $this->success("提交成功");
            } else {
                $this->error(__('The data is waiting for approval'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 删除
     * @param array $ids
     * @throws Throwable
     */
    public function del(array $ids = []): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }
        //删除审核
        $Pdata = [];
        $id = $ids[0];
        $row = $this->model->find($id);
        $OldJson = json_encode($row);
        $NewJson = json_encode("");
        // 库存信息记录删除

        $data['is_approval'] = 1;
        $row->save($data);
        // 提交记录

        $Approval = new Approval();
        $res = $Approval->AddApprovalRecord($OldJson,$NewJson,1,$ids[1],$this->auth->id);
        if ($res) {
            $this->success("提交成功");
        } else {
            $this->error(__('The data is waiting for approval'));
        }
    }
    /**
     * 判断编码是否重复
     */
    public function PartsCodeIsItRepeated($code,$num):void
    {
        $nur = $this->model->where("parts_code",$code)->count();
        if($nur>$num)
        {
            $this->error(__('配件编码已存在，请修改后重试！'));
        }
    }
    /**
     * 加载为select(远程下拉选择框)数据，默认还是走$this->index()方法
     * 必要时请在对应控制器类中重写
     */
    public function select(): void
    {
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $key_words = $this->request->param("quickSearch");
        // 不报错说明是下拉框的请求接口。
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->whereOr([["parts_name","like","%".$key_words."%"],[["parts_py","like","%".$key_words."%"]]])
            ->paginate();
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}